// 云函数入口文件
const cloud = require('wx-server-sdk')
const rp = require('request-promise')

cloud.init()

const MAX_LIMIT = 100
const db = cloud.database()
const URL = 'http://musicapi.xiecheng.live/personalized'

// 云函数入口函数
exports.main = async(event, context) => {
  // 处理获取数据条数的限制
  const countResult = await db.collection('playlist').count()
  const total = countResult.total
  const batchTimes = Math.ceil(total / MAX_LIMIT)
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    let promise = db.collection('playlist').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    tasks.push(promise)
  }
  let list = {
    data: []
  }
  if (tasks.length > 0) {
    // 不明白
    list = (await Promise.all(tasks)).reduce((acc, cur) => {
      return {
        data: acc.data.concat(cur.data)
      }
    })
  }
  console.log(list.data.length)

  // 只能查询100条数据
  // const list = await db.collection('playlist').get()
  const playlist = await rp(URL).then(res => {
    return JSON.parse(res).result
  })

  // 歌单数据去重
  const newDate = []
  for (let i = 0; i < playlist.length; i++) {
    let flag = true
    for (let j = 0; j < list.data.length; j++) {
      if (playlist[i].id === list.data[j].id) {
        flag = false
        break
      }
    }
    if (flag) {
      newDate.push(playlist[i])
    }
  }

  // 只能一条一条数据插入数据库
  for (let i = 0; i < newDate.length; i++) {
    await db.collection('playlist').add({
      data: {
        ...newDate[i],
        createTime: db.serverDate()
      }
    }).then(res => {
      // console.log(res)
      console.log('插入成功')
    }).catch(err => {
      // console.log(err)
      // console.log('插入失败')
    })
  }
}